import React, { createContext, useContext, useState, useRef } from 'react';
import Taro from '@tarojs/taro';

interface AudioContextType {
  currentPlayingId: string | null;
  play: (id: string, audioUrl: string) => void;
  pause: () => void;
  isPlaying: (id: string) => boolean;
}

const AudioContext = createContext<AudioContextType>({
  currentPlayingId: null,
  play: () => {},
  pause: () => {},
  isPlaying: () => false,
});

export const useAudio = () => useContext(AudioContext);

export const AudioProvider: React.FC<{children: React.ReactNode}> = ({ children }) => {
  const [currentPlayingId, setCurrentPlayingId] = useState<string | null>(null);
  const audioRef = useRef<Taro.InnerAudioContext | null>(null);
  
  // 播放音频
  const play = (id: string, audioUrl: string) => {
    // 如果当前有音频在播放，先停止它
    if (audioRef.current) {
      audioRef.current.stop();
      audioRef.current.destroy();
    }
    
    // 创建新的音频上下文
    audioRef.current = Taro.createInnerAudioContext();
    audioRef.current.src = audioUrl;
    audioRef.current.onEnded(() => {
      setCurrentPlayingId(null);
    });
    audioRef.current.onStop(() => {
      setCurrentPlayingId(null);
    });
    audioRef.current.onError(() => {
      setCurrentPlayingId(null);
    });
    
    // 播放新音频
    audioRef.current.play();
    setCurrentPlayingId(id);
  };
  
  // 暂停当前播放的音频
  const pause = () => {
    if (audioRef.current) {
      audioRef.current.pause();
      setCurrentPlayingId(null);
    }
  };
  
  // 检查指定ID的音频是否正在播放
  const isPlaying = (id: string) => {
    return id === currentPlayingId;
  };
  
  const value = {
    currentPlayingId,
    play,
    pause,
    isPlaying,
  };
  
  return (
    <AudioContext.Provider value={value}>
      {children}
    </AudioContext.Provider>
  );
};